package com.management.demo.controller.wx;

import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.management.demo.common.dto.PageDTO;
import com.management.demo.domain.wx.WxOrder;
import com.management.demo.dto.wx.OrderDTO;
import com.management.demo.dto.wx.OrderQueryDTO;
import com.management.demo.service.WxOrderService;
import com.management.demo.utils.OrderNumberUtils;
import com.management.demo.vo.wx.CartResultVO;
import com.management.demo.vo.wx.OrderVO;
import com.management.demo.common.vo.PageVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Tag(name = "订单接口")
@RestController
@RequestMapping("wx/order")
public class WXOrderController {

    @Autowired
    private WxOrderService wxOrderService;

    @Operation(summary = "生成订单")
    @PostMapping("create")
    public SaResult createOrder(@RequestBody OrderDTO orderDTO) {
        String orderId = OrderNumberUtils.generateOrderNumber();
        WxOrder wxOrder = BeanUtil.copyProperties(orderDTO, WxOrder.class);
        wxOrder.setId(orderId);
        boolean result = wxOrderService.save(wxOrder);
        return SaResult.ok().setData(result);
    }

    @Operation(summary = "分页查询订单")
    @PostMapping("page")
    public SaResult page(@RequestBody OrderQueryDTO orderQueryDTO) {
        String id = orderQueryDTO.getId();
        Integer wxId = orderQueryDTO.getWxId();
        Integer currentPage = orderQueryDTO.getCurrentPage();
        Integer pageSize = orderQueryDTO.getPageSize();

        LambdaQueryWrapper<WxOrder> queryWrapper = new LambdaQueryWrapper<WxOrder>()
                .like(StringUtils.isNotBlank(id), WxOrder::getId, id)
                .eq(wxId != null, WxOrder::getWxId, wxId)
                .orderByDesc(WxOrder::getCreateTime);
        Page<WxOrder> wxOrderPage = wxOrderService.page(new Page<>(currentPage, pageSize), queryWrapper);

        PageVO<OrderVO> orderPageVO = PageDTO.getPageVO(wxOrderPage, item -> {
            OrderVO orderVO = BeanUtil.copyProperties(item, OrderVO.class, "cartResultVO");
            CartResultVO cartResultVO = JSONUtil.toBean(item.getOrderList(), CartResultVO.class);
            orderVO.setCartResultVO(cartResultVO);
            return orderVO;
        });
        return SaResult.ok().setData(orderPageVO);
    }
}
